package ua.epam.muzalevskiy.traction.controllers;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import ua.epam.muzalevskiy.traction.commands.Command;
import ua.epam.muzalevskiy.traction.configuretion.MessageConfigurer;
import ua.epam.muzalevskiy.traction.configuretion.PagePathConfigurer;
import ua.epam.muzalevskiy.traction.configuretion.PageViewConfigurer;

/**
 * <code>Controller</code> class realizes the controller of the MVC pattern.
 * Current class gets command from the request and redirects user 
 * to the appropriate page returned by this command.
 *
 * @author Muzalevskiy Vitaliy
 */
public class Controller extends HttpServlet {

    private RequestHelper requestHelper;
    //logger is used to log MainController class
    private static Logger logger = Logger.getLogger(Controller.class);

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String page;
        try {
            //gets command from the request
            Command command = requestHelper.getCommand(request);
            logger.debug("command = " + command.toString());
            //executes the command and gets the page to forward user to
            page = command.execute(request, response);
            logger.debug("page = " + page);
        } catch (ServletException e) {
            logger.error(e.getLocalizedMessage());
            /* defines error message in case of ServletException and puts it as
             * the request attribute*/
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE,
                    MessageConfigurer.getInstance().getProperty(
                    MessageConfigurer.SERVLET_EXCEPTION_ERROR_MESSAGE));
            //sets page as an error page
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage());
            /* defines error message in case of IOException and puts it as
             * the request attribute*/
            request.setAttribute(Command.ATTRIBUTE_NAME_ERROR_MESSAGE,
                    MessageConfigurer.getInstance()
                    .getProperty(MessageConfigurer.IO_EXCEPTION_ERROR_MESSAGE));
            // sets page as an error page
            page = PagePathConfigurer.getInstance()
                    .getProperty(PagePathConfigurer.ERROR_PAGE);
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(page);
        dispatcher.forward(request, response);
    }

    @Override
    public void init() {
        requestHelper = RequestHelper.getInstance();
        getServletContext().setAttribute("config", PageViewConfigurer.getInstance());
        logger.debug("-----Main Controller Initialized------");
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
